from flask import Flask, Response, url_for, render_template, jsonify
import cv2
import numpy as np

app = Flask(__name__)
import datetime

# RTSP流地址
rtsp_url = 'rtsp://192.168.76.113/live.sdp'

def generate_frames():
    cap = cv2.VideoCapture(rtsp_url)

    if not cap.isOpened():
        print("无法连接到RTSP流")
        exit()

    try:
        while True:
            # 读取一帧
            ret, frame = cap.read()

            # 转换为JPEG并yield
            if ret:
                ret, buffer = cv2.imencode('.jpg', frame)
                frame = buffer.tobytes()
                yield (b'--frame\r\n'
                       b'Content-Type: image/jpeg\r\n\r\n' + frame + b'\r\n')
            else:
                break
    except Exception as e:
        print(f"Error: {e}")
    finally:
        cap.release()



@app.route('/video_feed')
def video_feed():
    return Response(generate_frames(), mimetype='multipart/x-mixed-replace; boundary=frame')

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)
